package com.example.myblog.controller;

import org.apache.commons.io.IOUtils;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.controller
 * @ClassName LoadController
 * @CreateTime: 2025-06-03  21:20
 * @Author: TangLiFei
 */
@Controller
public class LoadController {

    @GetMapping("/uploadPic")
    public String addForm() {
        return "upload";
    }
    //文件的上传
    @RequestMapping("/upload")
    public String upload(MultipartFile file,String desc){
        System.out.println("文件描述："+desc);
        File target=new File("D:/upload/upload-pic");
        //上传的原始文件名
        String originalFilename=file.getOriginalFilename();
        String fileName=UUID.randomUUID().toString()+originalFilename;
        target=new File(target,fileName);
        try {
            file.transferTo(target);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/getPics";
    }

    //文件的下载
    @RequestMapping("/download")
    public void downLoadFile(String fileName,  HttpServletResponse response){
        String realpath="D:\\upload\\upload-pic";
        File file=new File(realpath,fileName);
        try {
            InputStream in=new FileInputStream(file);
            OutputStream out= response.getOutputStream();
            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
            IOUtils.copy(in,out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取文件列表
    @RequestMapping("/getPics")
    public String  getPicList(Model model){
        String realpath="D:\\upload\\upload-pic";
        File file=new File(realpath);
        File[] files= file.listFiles();
        List<String> filenames=new ArrayList<>();
        for(File f:files){
            String name= f.getName();
            filenames.add(name);
        }
        model.addAttribute("filenames",filenames);
        return "showpic";
    }
}